require(['init'], function () {
    var $pagination = $('#js-pagination')
    var pagination;
    var curId = ''; //当前记录的id
    var $orderAdd;
    var $J_teacher_appoint = $('<div class="teacher-appoint" id="J_teacher_appoint" style="width:100%;">' +
        '<input type="hidden" id="oruid">' +
        '<input type="hidden" class="studentuid">' +
        '<input class="form-control " type="hidden" id="studentname">' +
        '<input class="form-control " type="hidden" id="coursename" >' +
        '<div class="line"></div>' +
        '<div class="TeachersQuery" style="width: 55%; float: left; border-bottom：none !important; height:100%; margin-top: 20px; border-radius: 5px">' +
        '<div class="topbar clearafter" style="margin-left:15px;height:94px">' +
        '<div class="teacher-search">' +
        '<p><a href="javascript:(void);">'+i18next.t('table.studentname')+'：</a><span id="studentname1" style="margin-right:15px;"></span>' +
        '<a href="javascript:(void);">'+i18next.t('table.course')+'：</a><span id="coursename1" style="margin-right:52px;"></span></p><br/>' +
        '<span>'+i18next.t('table.teacherquery')+'：</span>' +
        '<input type="text" id="J_date_search" class="form-control" data-type="date-input" data-tips="请选择日期范围" data-valuetype="range" readonly="" value="请选择日期范围" style="width: 210px;">' +
        '<select id="cource"></select>' +
        '</div>' +
        '</div>' +
        '<div class="wrap">' +
        '<table class="table" id="J_teacherlist_select">' +
        '<thead>' +
        '<th>'+i18next.t('table.no')+'</th>' +
        '<th>'+i18next.t('table.name')+'</th>' +
        '<th>'+i18next.t('table.starttime')+'</th>' +
        '<th>'+i18next.t('table.endtime')+'</th>' +
        '<th>'+i18next.t('table.remainingquota')+'</th>' +
        '<th>'+i18next.t('table.choice')+'</th>' +
        '</thead>' +
        '<tbody id="J_teacherlist_data"></tbody>' +
        '</table>' +
        '</div>' +
        '</div>' +
        '<div class="timelist-search" style="width: 42%; float: right; margin-left: 30px; border-bottom：none; height:auto;  border-left: 1px solid #ccc; margin-top: 20px;">' +
        '<h3 style="margin-left:15px;">'+i18next.t('table.make')+'</h3>' +
        '<div class="teacher" style="margin-left:15px;">' +
        '<span>'+i18next.t('info.teachername')+'：</span>' +
        '<span id="J_teachername"></span>' +
        '<ul class="teacherRemark" style="display:inline-block;margin-left:30px;"></ul>' +
        '</div>' +
        '<div class="duration" style="margin-left:15px;"></div>' +
        '<div class="appoint-section23" style="margin-left:15px;"></div>' +
        '</div>' +
        '<div style="width: 42%; float: right; margin-left: 30px; border-bottom：none; height: 980px;  border-left: 1px solid #ccc; margin-top: 20px;display:none" class="prompt">' +
        '<p style="margin-top:154px;margin-left:77px;">'+i18next.t('table.clickleft')+'</p>' +
        '</div>' +
        '</div>');
    var $orderEdit = $('<div class="paraList Nformstyle" id="J_enroll_wrap" >' +
        '<input class="form-control " type="hidden" name="orderuid">' +
        '<input class="form-control " type="hidden" name="studentuid" >' +
        '<div class="li Snameinput">' +
        '<div class="title  required">' +
        '<span>'+i18next.t('info.studentname')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control a1 focus studentname" data-formcheck="length" type="text" name="studentname"  readonly>' +
        '<div class="inputErrorTips" style="display: none;"></div>' +
        '</div>' +

        ' </div>' +
        '<div class="li">' +
        '<div class="title required">' +
        '<span>'+i18next.t('info.classinaccountnumber')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control focus a1" type="text" name="ClassInNo"  readonly>' +
        '<div class="inputErrorTips" style="display: none;"></div>' +
        '</div>' +
        '</div>' +
        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.classhour')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control a1" type="text" data-formcheck="number" name="classhours" >' +
        '</div>' +
        '</div>' +
        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.giveclass')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control a1" type="text" name="classbonus" >' +
        '</div>' +
        '</div>' +
        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.coursename')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control  a1" type="text" data-formcheck="length" name="coursename" >' +
        '</div>' +
        '</div>' +

        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.entrydate')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input type="text" class="form-control a1" size="16" data-type="date-input" name="orderdate" data-valuetype="single" data-value="0" value="选择时间" readonly="readonly"  style="width:177px;">' +
        '</div>' +
        '</div>' +

        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.describes')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control a1" type="text" name="description" >' +
        '</div>' +
        '</div>' +
        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.moneys')+'：</span>' +
        '</div>' +
        '<div class="content" style="position:relative;">' +
        '<input class="form-control a1" type="text" name="amount" style="padding-left:15px;width:177px" id="ordersinputpadding">' +
        '<span style="position:absolute;left:5px;top:6px" id="orderspanhide">￥</span>' +
        '</div>' +
        '</div>' +

        '</div>');
    $J_teacher_appoint.find('.line').css({
        "width": "1px",
        "height": "326px",
        "background": "#ccc",
        "position": "absolute",
        "left": "598px",
        "top": "30px",
        "z-index": "10000"
    })
    //获取信息
    function getorderinfos(querystr, cb) {
        var url = '/api/appointments';
        var query = {}
        if (querystr) {
            query = querystr
        }
        ajaxMethod({
            url: url,
            data: query,
            type: 'get',
            dataType: 'json',
            success: function (data) {
                cb && cb(data)
                if (data.list.length == 0) {
                    $('#J_enrollment').html('<div style="margin-top: 50px;text-align: center;">'+i18next.t('input.nullresults')+'</div>');
                    $pagination.hide()
                    return;
                }
                var $enrollmentTable = $('#J_enrollment').html('')
                var $thead = $('<thead>\
                <tr>\
                  <th>'+i18next.t('table.no')+'</th>\
                  <th>'+i18next.t('info.studentname')+'</th>\
                  <th>'+i18next.t('info.classinaccountnumber')+'</th>\
                  <th>'+i18next.t('table.classhours')+'</th>\
                  <th>'+i18next.t('table.giveclass')+'</th>\
                  <th>'+i18next.t('table.totalhours')+'<small style="font-size:6px;">'+i18next.t('table.classhoursadd')+'</small></th>\
                  <th>'+i18next.t('table.appointmentclass')+'</th>\
                  <th>'+i18next.t('table.coursename')+'</th>\
                  <th><a herf="javascript:;" >'+i18next.t('table.entrydate')+'</a></th>\
                  <th>'+i18next.t('table.entryman')+'</th>\
                  <th>'+i18next.t('table.orderhandle')+'</th>\
                  <th>'+i18next.t('table.handle')+'</th>\
               </tr>\
               </thead>').appendTo($enrollmentTable)
                var $tbody = $('<tbody></tbody>').appendTo($enrollmentTable);
                $.each(data.list, function (index, item) {
                    var coursename = "";
                    if (item.coursename != "") {
                        coursename = item.coursename;
                    } else {
                        coursename = "--";
                    }
                    var oruid = item.appointid;
                    var studentuid = item.studentuid;
                    var classhours = Number(item.classhours);
                    var classbonus = Number(item.classbonus);
                    var orderTime = formatTime(item.orderdate);
                    var $enroll = $('<tr class="enroll" data-uid="' + oruid + '"   data-studentuid="' + studentuid + '"  id="oder' + oruid + '"></tr>')
                    $enroll.append('<td>1</td>')
                    $enroll.append('<td>' + item.studentname + '</td>')
                    $enroll.append('<td>' + item.ClassInNo + '</td>')//这里的mobile实际是classInNo的字段
                    $enroll.append('<td  >' + classhours + '</td>')
                    $enroll.append('<td >' + classbonus + '</td>')
                    $enroll.append('<td >' + (classhours + classbonus) + '</td>')
                    var $alreadyhours = $('<td ><input type="button" class="btn btn-primary btn-sm btn-inverse appointhours"  value=' + item.consumed + '  style="background:#fff;"></td>').appendTo($enroll);
                    $enroll.append('<td>' + coursename + '</td>')
                    $enroll.append('<td>' + orderTime.substr(0, 10) + '</td>')
                    $enroll.append('<td>' + item.creator + '</td>')
                    var $bookbtn = $('<td ><input type="button" value="约课" class="ml5 btn btn-primary btn-sm btn-inverse" nam="arrbook" style="background:#fff;"></td>').appendTo($enroll);
                    $bookbtn.find('input').val(i18next.t('popupbox.aboutclass'));
                    var $handleTd = $('<td></td>').appendTo($enroll);
                    var $levelBtn = $('<span class="btn btn-primary btn-sm btn-inverse ml5">'+i18next.t('table.levelmanagement')+'</span>').appendTo($handleTd)
                    $levelBtn.on('click', function () {
                        var $wrapper = $('<div class="level-admin">\
                          <div id="tree" class="ztree"></div>\
                        </div>')
                        var popUpBox = new PopUpBox({
                            type: 'dom',
                            style: 'default contentScroll',
                            submitBtnType: 'confirm',
                            titleText:i18next.t('popupbox.courselevel'),// '课程级别'
                            drag: true,
                            show: true,
                            content: $wrapper,
                            callback: {
                                yes: function (e) {
                                    var treeObj = $.fn.zTree.getZTreeObj('tree');
                                    var node = treeObj.getCheckedNodes()

                                    if (!node.length) {
                                        _Tips(i18next.t('popupbox.pleaselevel'))//'请选择课程级别'
                                        return false
                                    }

                                    var ids = $.map(node, function (item) {
                                        return item.id
                                    })

                                    ajaxMethod({
                                        url: '/api/appointment/' + item.appointid + '/levels',
                                        method: 'put',
                                        data: {
                                            levels: ids
                                        },
                                        success: function (data, status) {
                                            if (status.code == 0) {
                                                getorderinfos()
                                                popUpBox.close()
                                            }
                                        }
                                    })

                                    return false;
                                }
                            },
                            position: {
                                width: 600,
                                height: 500
                            }
                        })
                        ajaxMethod({
                            url: '/api/appointment/' + item.appointid + '/levels',
                            success: function (data, status) {
                                var ids = $.map(data, function (item) {
                                    return item.id
                                })

                                if (status.code == 0) {
                                    levelTree({
                                        showRemoveBtn: function () {
                                            return false
                                        },
                                        showRenameBtn: function () {
                                            return false
                                        },
                                        showAddBtnFlag: false,
                                        setCheckNodes: function (wrapperIdName) {
                                            var treeObj = $.fn.zTree.getZTreeObj(wrapperIdName);
                                            var nodes = treeObj.getNodes();
                                            if (nodes.length > 0) {
                                                var node = treeObj.getNodesByFilter(function (node) {
                                                    return ids.indexOf(node.id) > -1
                                                })

                                                $.each(node, function (i, item) {
                                                    treeObj.checkNode(item);
                                                })
                                            }
                                        },
                                        checkEnable: true
                                    })
                                }
                            }
                        })


                    })
                    var $deletebtn = $('<a class="ml5 editOrder" ><span class="btn btn-primary btn-sm btn-inverse" >'+i18next.t('table.compile')+'</span></a>').appendTo($handleTd);
                    var $debtn = $('<a href="javascript:;"><span class="	btn btn-danger btn-sm btn-inverse">'+i18next.t('table.delete')+'</span></a>').appendTo($handleTd);
                    var sumn = (classhours) + (classbonus);
                    var inputVlue = parseInt($alreadyhours.find('input').val());
                    if (inputVlue >= sumn) {
                        $bookbtn.find("input").attr("disabled", "disabled");
                    } else {
                        $bookbtn.find("input").removeAttr("disabled");
                    }
                    //点击约课
                    $bookbtn.on('click', function () {
                        $J_teacher_appoint.find("#oruid").val(item.appointid);
                        $J_teacher_appoint.find(".studentuid").val(studentuid);
                        $J_teacher_appoint.find('#studentname').val(item.studentname);
                        $J_teacher_appoint.find('#coursename').val(item.coursename);
                        appointTeacher(callback);//按照时间选择老师
                        //判断该生有无约课级别，若无toast“设置。。。”，有则正常执行
                        function callback() {
                            coursetypes();//按照课程类型选择老师
                            var popUpBox = new PopUpBox({
                                type: 'dom',
                                style: 'default autoResize',
                                submitBtnType: 'alert',
                                closeClear: false,
                                titleText: i18next.t('popupbox.pleaseselectteacher'),//'请选择老师'
                                show: true,
                                content: $J_teacher_appoint,
                                callback: {
                                    yes: function (e) {
                                        window.location.reload();
                                    }

                                },
                                position: {
                                    width: 1042,
                                    height: 510,
                                }
                            })
                            popUpBox.submitBtnBox.$dom.css('text-align', 'right')
                        }

                    })
                    //点击编辑按钮
                    $deletebtn.on('click', function () {
                        loadEnrollData(oruid);
                        ClearError($orderEdit);
                        var popUpBox = new PopUpBox({
                            type: 'dom',
                            style: 'default contentScroll',
                            submitBtnType: 'confirm',
                            titleText:i18next.t('popupbox.editcontent'),// '请输入编辑内容'
                            show: true,
                            content: $orderEdit,
                            callback: {
                                yes: function (e) {
                                    var formcheck=FormCheck.childrenInputCheck($orderEdit);//非空校验
                                    if(formcheck){
                                        bindSubmit();
                                        window.location.reload();
                                    }else{
                                        return false;
                                    }


                                }
                            },
                            position: {
                                width: 750,
                                height: 352
                            }
                        })
                    })
                    //点击删除按钮
                    $debtn.on('click', function () {
                        var popUpBox = new PopUpBox({
                            type: 'dom',
                            style: 'default contentScroll',
                            submitBtnType: 'confirm',

                            titleText: i18next.t('popupbox.warmprompt'),//'温馨提示'
                            show: true,
                            content: '<div style="margin-left:27px;margin-top:34px;">'+i18next.t('popupbox.studentinfo')+'</div>',
                            callback: {
                                yes: function (e) {
                                    ajaxMethod({
                                        url: "/api/appointment/" + oruid,
                                        type: "delete",
                                        success: function () {
                                            //getorderinfos();
                                            pagination.updateData()
                                        }
                                    });
                                }
                            },
                            position: {
                                width: 448,
                                height: 226
                            }
                        })


                    })
                    $tbody.append($enroll);
                    var len = $('table tr').length;
                    for (var i = 1; i < len; i++) {
                        $('table tr:eq(' + i + ') td:first').text(i);
                    }

                    //处理空数据
                    $tbody.find("tr").each(function () {
                        var tdhtml = $(this).children();
                        $.each(tdhtml, function (i, t) {
                            //console.log($(t).text());
                            $(t).text() == 'null' ? $(t).text('--') : $(t).text()
                            $(t).text() == 'NaNaN-aN-a' ? $(t).text('--') : $(t).text()
                            $(t).text() == ' ' ? $(t).text('--') : $(t).text()
                            $(t).text() == '0000-00-00' ? $(t).text('--') : $(t).text()

                        })
                    });
                    //已约课按钮设置
                    var $appointhours = $alreadyhours.find("input");
                    if (item.consumed == 0) {
                        $appointhours.attr('disabled', true);
                    } else {
                        $appointhours.attr('disabled', false);
                    }
                    //点击已约课时数量
                    $alreadyhours.on("click", function () {
                      var stname=item.studentname;
                        ajaxMethod({
                            url: '/api/appointment/' + oruid + '/appints',
                            type: 'get',
                            dataType: 'json',
                            success: function (data) {
                                var $div = $('<div class="Yuelist wrap"></div>');
                                var $table = $('<table class="table enrollment" id="YueClasslist" style="margin-top:15px;"></table>').appendTo(($div));
                                var $thead = $('<thead>\
                                    <tr>\
                                      <th>'+i18next.t('table.no')+'</th>\
                                      <th>'+i18next.t('table.lessonsname')+'</th>\
                                      <th>'+i18next.t('info.teachername')+'</th>\
                                      <th>'+i18next.t('table.startdate')+'</th>\
                                      <th>'+i18next.t('table.time')+'</th>\
                                      <th>'+i18next.t('table.duration')+'</th>\
                                      <th>'+i18next.t('table.handle')+'</th>\
                                    </tr>\
                                    </thead>').appendTo($table);
                                var $tbody = $('<tbody></tbody>').appendTo($table);
                                function getDurationMinute(begintime, endtime) {
                                  if (begintime != null || endtime != null) {
                                      var begintime = +new Date(begintime.replace(' ', ' '));
                                      var endtime = +new Date(endtime.replace(' ', ' '));
                                      return (endtime - begintime) / (60 * 1000) + i18next.t('table.minute');
                                  } else {
                                      return '--';
                                  }
                                }
                                var studentname;
                                $.each(data, function (index, item) {
                                    var id = item.id,uid = item.scheduleid,begintime = new Date(item.begintime).Format('YYYY-MM-DD hh:mm')
                                    var endtime = new Date(item.endtime).Format('YYYY-MM-DD hh:mm');
                                    var $valuetr = $('<tr class="enroll" data-uid="' + uid + '"></tr>')
                                    $valuetr.append('<td>1</td>')
                                    var $schedule=$('<td></td>').appendTo($valuetr);
                                    $valuetr.append('<td>' + item.teacher + '</td>')
                                    $valuetr.append('<td>' + begintime.substr(0, 10) + ' </td>')
                                    $valuetr.append('<td>' + begintime.substr(11, 5) + '</td>')
                                    $valuetr.append('<td>' + getDurationMinute(item.begintime, item.endtime) + '</td>')
                                    var $affirm = $('<td><a  class="ml5 btn btn-warning">'+i18next.t('table.cancel')+'</a></td>').appendTo($valuetr);
                                    ajaxMethod({
                                        url: '/api/schedule/'+item.scheduleid,
                                        type: 'get',
                                        success: function (data) {
                                            if(data.scheduleid==item.scheduleid){
                                              $('<a>'+(data.name==null?"--":data.name)+'</a>').appendTo($schedule);
                                            }
                                          }
                                      })
                                    $affirm.on('click', function () {
                                      ajaxMethod({
                                        url: '/api/appointment/' + id + '/unappint',
                                        type: 'put',
                                        success: function (data,status) {
                                        if(status.code != 0){
                                          var popUpBox = new PopUpBox({
                                              type: 'dom',
                                              style: 'default contentScroll',
                                              submitBtnType: 'confirm',
                                              titleText:i18next.t('popupbox.systemmessages') ,//'系统提示'
                                              show: true,
                                              content: '<p style="margin-left:18px;margin-top:21px;">'+i18next.t('popupbox.nocancel')+'</p>',//该课程已经结束或正在上课，不能取消！
                                              callback: {
                                                  yes: function (e) {
                                                  }
                                              },
                                              position: {
                                                  width:435,
                                                  height: 300
                                              }
                                          })
                                          $(".btn-default").css({
                                           'border':'1px solid #ccc'
                                          });
                                        }else{
                                          $affirm.find('input').attr('disabled',true);
                                          location.reload();
                                        }
                                       }
                                      })
                                    })
                                    $tbody.append($valuetr);
                                    var len = $div.find('table tr').length;
                                    for (var i = 1; i < len; i++) {
                                        $div.find('table tr:eq(' + i + ') td:first').text(i);
                                    }
                                })
                                //弹出层
                                var popUpBox = new PopUpBox({
                                    type: 'dom',
                                    style: 'default contentScroll',
                                    submitBtnType: false,
                                    titleText: ''+i18next.t('info.studentname')+':　<span>' + stname + '</span>',
                                    show: true,
                                    content: $div,
                                    callback: {
                                        yes: function (e) {
                                        }
                                    },
                                    position: {
                                        width: 871,
                                        height: 500
                                    }
                                })
                              }
                        })
                    })
                })
                $pagination.show()
                //把所有null的字段都换成---
                $tbody.find("tr").each(function () {
                    var tdhtml = $(this).children();
                    $.each(tdhtml, function (i, t) {
                        $(t).text() == 'null' ? $(t).text('--') : $(t).text()
                        $(t).text() == '1970-01-01' ? $(t).text('--') : $(t).text()
                    })
                });
            }
        })
      }
    //报名表列表导入功能
    function fileUpload($container) {
        var $uploadInput = $container.find('input')
        var coverUploadInput = new UploadInput({
            formData: {
                importer: 'appoint'
            },
            $dom: $uploadInput,
            done: function (uploadSrc) {
	if(uploadSrc!="true"){
             var $import=$('<div style="padding-left:18px;margin-top:15px;"></div>').html('');
             $.each(uploadSrc,function(index,exce){
                $("<p style='height:30px;line-height:30px;'><label style='display:inline-block;width:85px;'>"+exce.student.studentname+":</label><label>"+exce.error+"</label></p>").appendTo($import);
             })
           }else{
             var $import=$('<div style="padding-left:18px;margin-top:15px;">'+i18next.t('popupbox.data')+'</div>');//数据已经导入成功！
           }
           var popUpBox = new PopUpBox({
               type: 'dom',
               style: 'default contentScroll',
               submitBtnType: 'confirm',
               keySubmit: false,
               titleText: i18next.t('popupbox.importdata'),//'导入信息提示'
               show: true,
               content: $import,
               callback: {
                   yes: function (e) {
                     window.location.reload();
                   }
               },
               position: {
                   width:450,
                   height:263
               }
           })
         }
       });
   }
   fileUpload($('#J_container'))
    //搜索
    function loadSearchData(querystr) {
        if (querystr) {
            pagination.filter.studentname = querystr;
            pagination.filter.ClassIn = querystr;
            pagination.searchData()
        } else {
            pagination.reloadData()
        }
    }

    $('#J_teacher_search').on('click', function () {
        var $input = $(this).prev();
        var querystr = $.trim($input.val());
        loadSearchData(querystr)
    });

    $('.searchInput').on('keyup', function (e) {
        if (e.keyCode == 13) {
            var querystr = $.trim($(this).val());
            loadSearchData(querystr)
        }
    });
    //添加学生
    $("#orderadd").on("click", function () {
        $orderAdd = $('<div class="paraList">' +
            '<input class="form-control " type="hidden" name="orderuid">' +
            '<input class="form-control " type="hidden" name="studentuid" >' +
            '<div class="li line">' +
            '<div class="title">' +
            '<label style="color:red";position: relative;left: -2px;>*</label><span>'+i18next.t('info.studentname')+'</span>' +
            '</div>' +
            '<div class="content" id="j-studencontainer">' +
            '<span class="btn btn-default" id="j-addstudent">'+i18next.t('info.addstudents')+'</span>' +
            '</div>' +
            '</div>' +
            '<div class="li">' +
            '<div class="title">' +
            '<label style="color:red";position: relative;left: -2px;>*</label><span>'+i18next.t('table.classhours')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input class="form-control a1" type="text" data-formcheck="number" name="classhours" >' +
            '</div>' +
            '</div>' +
            '<div class="li">' +
            '<div class="title">' +
            '<span>'+i18next.t('table.giveclass')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input class="form-control a1" type="text" name="classbonus" >' +
            '</div>' +
            '</div>' +
            '<div class="li">' +
            '<div class="title">' +
            '<label style="color:red";position: relative;left: -2px;>*</label><span>'+i18next.t('table.coursename')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input class="form-control a1" type="text" data-formcheck="length" name="coursename" >' +
            '</div>' +
            '</div>' +

            '<div class="li">' +
            '<div class="title">' +
            '<span>'+i18next.t('table.entrydate')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input type="text" class="form-control a1" size="16" data-type="date-input" name="orderdate" data-valuetype="single" data-value="0" value="选择时间" readonly="readonly"  style="width:170px;">' +
            '</div>' +
            '</div>' +

            '<div class="li">' +
            '<div class="title">' +
            '<span>'+i18next.t('table.describe')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input class="form-control a1" type="text" name="description" ">' +
            '</div>' +
            '</div>' +
            '<div class="li">' +
            '<div class="title">' +
            '<span>'+i18next.t('table.money')+'</span>' +
            '</div>' +
            '<div class="content" style="position:relative;">' +
            '<input class="form-control a1" type="text" name="amount" style="padding-left:15px;width:177px" id="ordersinputpadding" >' +
            '<span style="position:absolute;left:5px;top:7px" id="orderspanhide">￥</span>' +
            '</div>' +
            '</div>' +
            '</div>');
        var newda = new Date().Format('YYYY-MM-DD');
        $orderAdd.find('[name=orderdate]').val(newda);

        var $addStudentBtn = $orderAdd.find('#j-addstudent')
        var studentViewList = new ContactViewList({
            hasAvatar: true,
            editable: false
        })

        $addStudentBtn.after(studentViewList.$dom.addClass('inline-block').addClass('cursor-pointer'))

        function studentSelect() {
            ajaxMethod({
                url: '/api/students',
                success: function (data) {
                    var candidateStudentList = []
                    $.each(data, function (i, item) {
                        console.log(item);
                        candidateStudentList.push({
                            id: item.studentuid,
                            avatar: '../img/avatar.png',
                            name: item.name,
                            phone: item.ClassInNo
                        })
                    })

                    var studentSelector = new ContactSelector({
                        candidateDataList: candidateStudentList,
                        checkedDataList: studentViewList.getDataList(),
                        checkedMax: 1,
                        callback: {
                            submit: function (checkedDataList) {
                                if (!Object.keys(checkedDataList).length) {
                                    _Tips(i18next.t('popupbox.pleaseselect'));//'请选择'
                                    return false
                                }
                                console.log(checkedDataList);
                                $addStudentBtn.hide()

                                studentViewList.update(checkedDataList)
                            }
                        }
                    })
                    studentSelector.$titleText.html(i18next.t('info.addstudents'))//添加学生
                    studentSelector.popUpBox.show();
                }
            })
        }


        $addStudentBtn.on('click', function () {
            studentSelect();
        })

        studentViewList.$dom.on('click', function () {
            studentSelect();
        })


        var popUpBox = new PopUpBox({
            type: 'dom',
            style: 'default contentScroll',
            submitBtnType: 'confirm',
            titleText:i18next.t('popupbox.pleasecontent') ,//请填写内容
            show: true,
            content: $orderAdd,
            callback: {
                yes: function (e) {
                    if($(".contactViewList .hasAvatar").length==0){
                        _Tips("请先选择学生！");
                        return false;
                    }
                    var formcheck=FormCheck.childrenInputCheck($orderAdd);//非空校验
                    if(formcheck){
                        var $contact = $orderAdd.find('.contact');
                        function add() {
                            var appointid = $orderAdd.find('[name=orderuid]').val()
                            var orderstatus = $orderAdd.find('[name=orderstatus]').val()
                            var studentuid = $contact.attr('data-contactid');
                            var studentname = $contact.find('.name').text();
                            var mobile = $contact.find('.description').text();//选框组件
                            var classhours = $orderAdd.find('[name=classhours]').val()
                            var classbonus = $orderAdd.find('[name=classbonus]').val()
                            var courseid = $orderAdd.find('[name=courseid]').val()
                            var coursename = $orderAdd.find('[name=coursename]').val()
                            var orderdate = $orderAdd.find('[name=orderdate]').val()
                            var description = $orderAdd.find('[name="description"]').val()
                            var amount = $orderAdd.find('[name=amount]').val();
                            var Studentroll = {
                                orderstatus: orderstatus,
                                studentuid: studentuid,
                                studentname: studentname,
                                mobile: mobile,
                                classbonus: classbonus,
                                classhours: classhours,
                                courseid: courseid,
                                coursename: coursename,
                                orderdate: orderdate,
                                description: description,
                                amount: amount
                            };
                            ajaxMethod({
                                url: '/api/appointment',
                                type: 'post',
                                data: Studentroll,
                                success: function (data) {
                                    window.location.reload();
                                    //alert('添加成功')
                                }
                            });
                        }

                        var studentname = $contact.find('.name').text();
                        var classhours = $orderAdd.find('[name=classhours]').val();
                        if (studentname != "" || classhours != "") {
                            add();
                        } else {
                            return false;
                        }
                    }else{
                        return false;
                    }

                }
            },
            position: {
                width: 667,
                height: 352
            }
        })
    })

    function loadEnrollData(oruid, callback) {
        console.log(oruid)
        ajaxMethod({
            url: '/api/appointment/' + oruid,
            dataType: 'json',
            success: function (data) {
                $orderEdit.find('[name=orderuid]').val(data.appointid);
                $orderEdit.find('[name=orderstatus]').val(data.orderstatus);
                $orderEdit.find('[name=studentuid]').val(data.studentuid);
                $orderEdit.find('[name=studentname]').val(data.studentname);
                $orderEdit.find('[name=ClassInNo]').val(data.ClassInNo);
                $orderEdit.find('[name=classhours]').val(data.classhours);
                $orderEdit.find('[name=classbonus]').val(data.classbonus);
                $orderEdit.find('[name=courseid]').val(data.courseid);
                $orderEdit.find('[name=coursename]').val(data.coursename);
                $orderEdit.find('[name=description]').val(data.description);
                $orderEdit.find('[name=amount]').val(data.amount);
                var orderdate = "";
                if (data.orderdate != "0000-00-00 00:00:00") {
                    orderdate = data.orderdate.substr(0, 10)
                } else {
                    return i18next.t('popupbox.pleasedate');//请选择日期
                }
                $orderEdit.find('[name=orderdate]').val(orderdate);
                (typeof callback == 'function') && callback()
            }
        })
    }

    //编辑学生
    function bindSubmit(data) {
        if (FormCheck.childrenInputCheck($orderEdit.find('#J_enroll_wrap'))) {
            var appointid = $orderEdit.find('[name=orderuid]').val()
            var orderstatus = $orderEdit.find('[name=orderstatus]').val()
            var studentuid = $orderEdit.find('[name=studentuid]').val()
            var studentname = $orderEdit.find('[name="studentname"]').val()
            var ClassInNo = $orderEdit.find('[name=ClassInNo]').val()
            var classhours = $orderEdit.find('[name=classhours]').val()
            var classbonus = $orderEdit.find('[name=classbonus]').val()
            var courseid = $orderEdit.find('[name=courseid]').val()
            var coursename = $orderEdit.find('[name=coursename]').val()
            var orderdate = $orderEdit.find('[name=orderdate]').val()
            var description = $orderEdit.find('[name="description"]').val()
            var amount = $orderEdit.find('[name=amount]').val()
            var Studentroll = {
                orderstatus: orderstatus,
                studentuid: studentuid,
                studentname: studentname,
                ClassInNo: ClassInNo,
                classbonus: classbonus,
                classhours: classhours,
                courseid: courseid,
                coursename: coursename,
                orderdate: orderdate,
                description: description,
                amount: amount
            }
            if (appointid != undefined) {
                ajaxMethod({
                    url: '/api/appointment/' + appointid,
                    type: 'put',
                    data: $.extend(Studentroll, {appointid: appointid}),
                    success: function (data) {
                        //alert('修改成功')
                    }
                });

            }

        }
    }

    var scheduleidarr = [];
    //以下是点击预约的controller
    var checkedList = new Array();
    function getEnrollList(arr) {
        ajaxMethod({
            url: '/api/appointment/' + $J_teacher_appoint.find("#oruid").val() + '/levels',
            success: function (data, status) {
            if (status.code == 0) {
                ajaxMethod({
                    url: '/api/schedules/teachertimes',
                    type: 'get',
                    dataType: 'json',
                    data: $.extend(arr, {
                        levels: $.map(data, function (item) {
                            return item.id
                        })
                    }),
                success: function (data, arr) {
                    var $enrollmentTable1 = $J_teacher_appoint.find('.appoint-section23').html('');
                    var days = data.days;
                $.each(days, function (index, item) {
                    var a = JSON.stringify(item.day)
                    var day = (item.day).replace(/\-/g, "");
                    var $div = $('<div data-id=' + day + '></div>').appendTo($enrollmentTable1);
                    $div.append('<h4 style="margin-top:43px;">' + item.day + ' (' + item.week + ') ' + '</h4>');
                    var list = item.list;
                    console.log(scheduleidarr);
                  $.each(list, function (index2, item2) {
                  var $p = $("<p style='height:41px;margin:24px 0;'></p>").appendTo($div);
                  var spn1 = $('<span class="spn1" style="display:inline-block;width:337px;line-height:24px;"></span>').appendTo($p);
                  spn1.append('<span style="width:161px;display:inline-block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;position:relative;top:5px;">'+i18next.t('course.coursetype') +':' + item2.coursetypename + '</span>');
                  var $lessonName = $('<span style="margin-top:10px;cursor:pointer" class="cursor-edit">'+i18next.t('table.lessonsname') +'：<span style="max-width:68px;display: inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;position: relative;top: 10px;" class="J_lesson">' + item2.name + '</span></span><br/>')

                 $lessonName.on('click', function() {

                   var beforeVal = item2.name;
                   var $content = $('<div class="formList">\
                     <div class="formLi">\
                       <div class="formTitle">\
                         <span>'+i18next.t('table.lessonsname') +'</span>\
                       </div>\
                       <div class="formContent">\
                         <input class="form-control" type="text" name="lessonname" value="'+ beforeVal +'" style="width:300px;">\
                       </div>\
                     </div>\
                   </div>');
                   var $input = $content.find('[name="lessonname"]');

                   var popUpBox=new PopUpBox({
                     type:'dom',
                     style:'default',
                     submitBtnType:'confirm',
                     titleText:i18next.t('popupbox.edit'),//编辑课节名称
                     content:$content,
                     show: true,
                     callback:{
                       'yes':function(e){
                         var curVal = $.trim($input.val());
                         if(curVal == beforeVal) {
                           _Tips(i18next.t('popupbox.nochange'));//'课节名称无变化'
                           return false;
                         }

                         if(curVal == '') {
                           _Tips(i18next.t('popupbox.lessonnoempty'));//'课节名称不能为空'
                           return false
                         }

                         ajaxMethod({
                           url: '/api/schedule/' + item2.scheduleid,
                           method: 'put',
                           data: $.extend(item2, { name: curVal}),
                           success: function (data, status) {
                             if(status.code == 0) {
                               $lessonName.find('.J_lesson').text(data.name)
                               popUpBox.close()
                             }
                           }
                         })

                       }
                     },
                     position:{
                       width:450,
                       height:200
                     }
                   })
                 })

                spn1.append($lessonName)
                spn1.append('<span style="padding-right:29px;padding-left:4px;width:161px;display:inline-block;">'+i18next.t('table.time')+':' + (item2.begintime.substr(11, 5)) + '~' + (item2.endtime.substr(11, 5)) + '</span>');
                spn1.append('<span style="" >'+i18next.t('table.remainingquota')+'：<a class="quotas">' + item2.quotas + '</a></span>');
                      if(!localStorage.lang){
                          localStorage.setItem('lang','zh');
                      }
                      if(localStorage.lang && localStorage.lang=="zh"){
                          var $appointBtn1 = $('<input type="button" data-i18n="[value]table.make" value="预约" class="btn btn-primary" style="position: relative;left: 14px;top: -11px;">').appendTo($p);
                      }else{
                          var $appointBtn1 = $('<input type="button" data-i18n="[value]table.make" value="预约" class="btn btn-primary" style="position: relative;left: 170px;top: 0px;">').appendTo($p);
                      }
                $appointBtn1.val(i18next.t('table.make'));
                for (var i = 0; i < scheduleidarr.length; i++) {
                    if (scheduleidarr[i] == item2.scheduleid) {
                        $appointBtn1.attr("disabled", "disabled");
                        $appointBtn1.val(i18next.t('table.reservation'));//"已预约"
                    }
                }
                var quotas = 0;
                $appointBtn1.on('click', function () {
                    quotas = $(this).prev('span').find('.quotas').html() - 1;
                    if (quotas < 0) {
                        quotas = 0;
                    }
                    $(this).prev('span').find('.quotas').html(quotas);
                    $(this).attr("disabled", "disabled");
                    $(this).val(i18next.t('table.reservation'));//"已预约"
                    var oruid = $J_teacher_appoint.find("#oruid").val();
                    var studentuid = $J_teacher_appoint.find(".studentuid").val();
                    ajaxMethod({
                        url: "/api/appointment/"+oruid+"/appint",
                        dataType: "json",
                        type: 'put',
                        data: {"scheduleid":item2.scheduleid},
                        success:function(data,status){
                            if(status.code!=0){
                              $(this).css({
                                "background":"#ccc",
                                "border":"1px solid #ccc",
                                "color":"#fff"
                              });
                              //alert(i.message);
                              $(this).html(i18next.t('table.reservation'));//"已预约"
                               var popUpBox=new PopUpBox({
                                 type:'dom',
                                 style:'default',
                                 submitBtnType:'confirm',
                                 titleText:i18next.t('popupbox.edit'),//'编辑课节名称'
                                 content:'<div style="margin-left:20px;margin-top:20px;">'+status.message+'</div>',
                                 show: true,
                                 callback:{
                                   'yes':function(e){
                                     window.location.reload();
                                   }
                                 },
                                 position:{
                                   width:420,
                                   height:200
                                 }
                               })

                            }
                        }
                    })
                  })

               })
             })
             //排序
              function big() {
                  var tr = $enrollmentTable1.find("div");
                  var initList = [], domArr = [];

                  $.each(tr, function (a, k) {
                      initList[a] = $(this).attr('data-id');

                  })
                  /* 从小到大排序*/
                  function bigToSmall() {
                      getDom();
                      $.each(domArr, function (i) {
                          $.each(domArr, function (j) {
                              if (domArr[i].attr('data-id') < domArr[j].attr('data-id')) {
                                  mid = domArr[j];
                                  domArr[j] = domArr[i];
                                  domArr[i] = mid;
                              }

                          })
                      })
                      appendDom()
                  }

                  /*取出所有tr放进数组*/
                  function getDom() {
                      $(tr).each(function (m) {
                          domArr[m] = $(this);
                      })
                  }

                  /*将数组中的tr插入tbody(原ul中的li自动删除。DOM元素的特性。) */
                  function appendDom() {
                      $.each(domArr, function (d) {
                          $enrollmentTable1.append(domArr[d]);
                      })
                  }

                  bigToSmall();
              }
              big();
             }
            })
          }
        }
      })

    }

    //按照类型选择老师
    function coursetypes() {
        ajaxMethod({
            url: '/api/coursetypes',
            type: "get",
            dataType: "json",
            success: function (data) {
                cource(data);
            }

        })
        function cource(data) {
            //console.log(data)
            var $cource = $('#cource').html('');
            $('<option>'+i18next.t('table.all')+'</option>').appendTo($cource);
            $cource.css({
                "width": "120px",
                "height": "30px",
                "border": "1px solid #ccc",
                "border-radius": "3px"

            });

            $.each(data, function (index, item) {
                //console.log(item.coursetypeuid);
                $('<option data-cuid=' + item.coursetypeuid + '>' + item.coursetypename + '</option>').appendTo($cource);

            })
            $('#cource').on('change', function () {
                var sCoursetypename = $('#cource option:selected').val();
                var sCoursetypeid = $('#cource option:selected').attr('data-cuid');
                var getVal = $J_teacher_appoint.find("#J_date_search").val();
                appointTeacher(getVal.split('~')[0], getVal.split('~')[1], sCoursetypeid);
            })
        }
    }

    //按照时间选择老师
    function appointTeacher(begintime, endtime, sCoursetypeid,callback) {
        if (begintime == undefined) {
            begintime = new Date().Format('YYYY-MM-DD')

            endtime = new Date(+new Date + 30 * 24 * 3600 * 1000).Format('YYYY-MM-DD')
            $J_teacher_appoint.find('#J_date_search').val(begintime + '~' + endtime)
        }

        ajaxMethod({
            url: '/api/appointment/' + $J_teacher_appoint.find("#oruid").val() + '/levels',
            success: function (data, status) {
                if (data.length!=0){
                    callback && callback();
                }else{
                    _Tips("请先设置约课级别！");
                    return;
                }
                if (status.code == 0) {
                    ajaxMethod({
                        url: '/api/schedules/teachers',
                        data: {
                            begintime: begintime,
                            endtime: endtime,
                            coursetypeid: sCoursetypeid,
                            levels: $.map(data, function (item) {
                                return item.id
                            })
                        },
                        success: function (data,status) {
                            formatData(data, sCoursetypeid);
                        }
                    })
                }
            }
        })


        function formatData(data, sCoursetypeid) {
            var $teacherListData = $J_teacher_appoint.find('#J_teacherlist_data').html('')
            $.each(data, function (index, item) {
                var studentname = $J_teacher_appoint.find('#studentname').val();
                var coursename = $J_teacher_appoint.find('#coursename').val();
                $J_teacher_appoint.find("#studentname1").html(studentname==""?"--":studentname);
                $J_teacher_appoint.find("#coursename1").html(coursename);
                var teacheruid = item.teacherid;
                var $tr = $('<tr id="id' + item.teacherid + '" data-uid="' + item.teacherid + '"></tr>')
                $tr.append('<td>1</td>')
                $tr.append('<td>' + item.teachername + '</td>')
                $tr.append('<td>' + item.begintime + '</td>')
                $tr.append('<td>' + item.endtime + '</td>')
                $tr.append('<td>' + item.times + '</td>')
                var $radioTd = $('<td></td>').appendTo($tr)
                var $radioIcon = $('<span class="icon icon-size-16 icon-radio" data-type="checkbox" style="postion:relative;left:-3px;">\
               <input type="checkbox" name="teacher" data-checkedmax="1" value="1">\
               </span>').appendTo($radioTd);
                //点击小点
                $radioIcon.on('click', function () {
                    var oruid = $J_teacher_appoint.find("#oruid").val();
                    //alert(oruid);
                    ajaxMethod({
                        url: "/api/appointment/" + oruid + "/appints",
                        type: "get",
                        dataType: "json",
                        success: function (data) {
                          $.each(data, function (index, item) {
                              scheduleidarr.push(item.scheduleid);
                          })
                        }
                      })
                    if ($(this).hasClass('checked')) {
                        $J_teacher_appoint.find('.timelist-search').hide()
                    } else {
                        $J_teacher_appoint.find('#J_teachername').text(item.teachername)
                        $J_teacher_appoint.find('.timelist-search').show()

                        teacherlist(sCoursetypeid);
                        $('#J_appointTimeList').click()
                        var $parentDom = $J_teacher_appoint.find('.appoint-section').html('');
                        var $teacherRemark = $J_teacher_appoint.find('.teacherRemark').html('');
                        var id = item.teacherid;
                        ajaxMethod({
                            url: "/api/teacher/" + id,
                            type: "get",
                            success: function (data) {
                                $('<a>'+i18next.t('popupbox.remark')+'：</a><li style="display:inline-block;">' + data.remark1 + ' ,</li><li  style="display:inline-block;padding:0 4px;">' + data.remark2 + '</li>').appendTo($teacherRemark);
                            }
                        })
                    }
                })


                function teacherlist(sCoursetypeid) {
                    var arr = {
                        begintime: item.begintime,
                        endtime: item.endtime,
                        teacherid: item.teacherid,
                        coursetypeid: sCoursetypeid
                    }

                    $('.timelist-search').show()
                    $('.prompt').hide();
                    $('#J_appointTimeList').click()
                    getEnrollList(arr);
                }


                $teacherListData.append($tr)
                var $J_teacherlist_select = $J_teacher_appoint.find('#J_teacherlist_select');
                var len = $J_teacherlist_select.find('tr').length;
                for (var i = 1; i < len; i++) {
                    $J_teacherlist_select.find('tr:eq(' + i + ') td:first').text(i);
                }

            })
        }


    }
    $J_teacher_appoint.find('#J_date_search').on('change', function () {
        var getVal = $(this).val()
        appointTeacher(getVal.split('~')[0], getVal.split('~')[1])
    })

    pagination = new Pagination($pagination, getorderinfos)
})
